<template>
  <v-menu offset-y>
    <template v-slot:activator="{ props }">
      <v-btn
        v-bind="props"
        variant="text"
        :prepend-icon="currentLanguage.flag"
      >
        {{ currentLanguage.name }}
        <v-icon>mdi-chevron-down</v-icon>
      </v-btn>
    </template>
    
    <v-list>
      <v-list-item
        v-for="(lang, code) in supportedLocales"
        :key="code"
        @click="switchLanguage(code)"
        :class="{ 'v-list-item--active': currentLocale === code }"
      >
        <template v-slot:prepend>
          <span class="mr-2">{{ lang.flag }}</span>
        </template>
        <v-list-item-title>{{ lang.name }}</v-list-item-title>
      </v-list-item>
    </v-list>
  </v-menu>
</template>

<script setup>
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { supportedLocales, setLocale, getCurrentLocale } from '@/locales'

const { locale } = useI18n()

const currentLocale = computed(() => getCurrentLocale())
const currentLanguage = computed(() => supportedLocales[currentLocale.value])

function switchLanguage(newLocale) {
  setLocale(newLocale)
}
</script>